package com.leetcode.weekly.contest.no286th;

import java.util.Arrays;

/**
 * @author 覃国强
 * @date 2022-03-27 11:04
 */
public class A02_找到指定长度的回文数 {

  public static void main(String[] args) {
    int[] queries = {90};
    Solution solution = new Solution();
    long[] longs = solution.kthPalindrome(queries, 3);
    System.out.println(Arrays.toString(longs));
  }


  static
  class Solution {
    public long[] kthPalindrome(int[] queries, int intLength) {
      if (queries == null || queries.length == 0) {
        return new long[0];
      }

      boolean hasAxis = intLength % 2 != 0;
      int leftNumCount = intLength / 2 + (hasAxis ? 1 : 0);
      long[] answer = new long[queries.length];
      for (int i = 0; i < queries.length; ++i) {
        answer[i] = getPalindrome(leftNumCount, hasAxis, queries[i]);
      }
      return answer;
    }

    private long getPalindrome(int leftNumCount, boolean hasAxis, int k) {
      long leftBase = getLeftBase(leftNumCount);

      long numCount = leftBase * 10 - leftBase;
      if (k > numCount) {
        return -1;
      }
      long leftTarget = leftBase + (k -  1);
      return getRealPalindrome(leftTarget, hasAxis);
    }

    private long getRealPalindrome(long leftTarget, boolean hasAxis) {
      long num = hasAxis ? leftTarget / 10 : leftTarget;
      while (num > 0) {
        long tmp = num % 10;
        num /= 10;
        leftTarget = leftTarget * 10 + tmp;
      }
      return leftTarget;
    }

    private long getLeftBase(int leftNumCount) {
      long base = 1;
      while (leftNumCount > 1) {
        base *= 10;
        --leftNumCount;
      }
      return base;
    }

  }

}
